class GroupsController < ApplicationController
    include AuthenticatedSystemBrowse
    
    before_filter :login_required, :only => [ :new, :create, :edit, :update, :update_icon, :join, :quit, :manage_users, :kick, :promote_to_admin, :degrade, :newpost ]
    #before_filter :admin_required, :only => [ :destroy ]
    
    def join
        group = Group.find(params[:id])
        if !current_user.is_group_user(group)
            group_users = GroupUser.new(:group => group, :user => current_user, :is_admin => 'f', :created_at => Time.now.utc)
            group_users.save!
        end
        redirect_to group_url(group )
    end
    
    def quit
        group = Group.find(params[:id])    
        if current_user.could_quit(group)
            group_users = GroupUser.find(:first, :conditions => ["user_id = ? and group_id = ?", current_user.id, group.id])
            group_users.destroy
        end
        redirect_back_or_default group_url(group)
    end
    
    def kick
        if params[:group] && params[:user]
            group_users = GroupUser.find(:first, :conditions => ["user_id = ? and group_id = ?", params[:user][:id], params[:group][:id]])
            group_users.destroy
            redirect_back_or_default manage_users_group_url(params[:group][:id])
        end
    end
    
    def promote_to_admin
        group = Group.find(params[:group][:id])
        user = User.find(params[:user][:id])
        if current_user.is_group_admin(group)
            group_users = GroupUser.find(:first, :conditions => ["user_id = ? and group_id = ?", user.id, group.id])
            group_users.is_admin = 't'
            group_users.save!
            redirect_back_or_default manage_users_group_url(group)
        else
            redirect_back_or_default manage_users_group_url(group)
        end
    end
    
    def degrade
        group = Group.find(params[:group][:id])
        user = User.find(params[:user][:id])
        if current_user.is_group_admin(group)
            group_users = GroupUser.find(:first, :conditions => ["user_id = ? and group_id = ?", user.id, group.id])
            group_users.is_admin = 'f'
            group_users.save!
            
            redirect_back_or_default manage_users_group_url(group)
        else
            redirect_back_or_default manage_users_group_url(group)
        end
    end
    
    def index
        respond_to do |format|
            format.html do
                if !current_user.nil?
                    @groups_admin = current_user.groups_admin
                    @mygroups = current_user.groups
                    if @mygroups.size > 0
                      @posts_at_mygroups = GroupPost.find(:all, :include => [ :user, :group ], :conditions => [ "group_id in (#{@mygroups.collect{|n| n.id}.join(',')})"], :order => 'replied_at desc')
                    end
                end
                @posts_at_allgroups = GroupPost.find(:all, :include => [ :user, :group ], :order => 'replied_at desc', :limit => 25)
                @new_groups = Group.find(:all, :order => 'created_at desc limit 18')
                @hot_groups = Group.find(:all, :order => 'group_posts_count desc limit 18')
                
                @page_title = '小组'
            end
            format.rss  do
                @posts = GroupPost.find(:all, :include => [:user, :group ], :order => 'replied_at desc', :limit => 25)
                render :action => "index.rxml", :layout => false
            end
        end
        
    end
    
    def search
        if params[:q].nil? || params[:q].blank?
            redirect_to_referer groups_url
        elsif params[:p_submit].nil?
            @new_groups = Group.find(:all, :order => 'created_at desc limit 18')
            @hot_groups = Group.find(:all, :order => 'group_posts_count desc limit 18')
            @groups = Group.paginate_search(params[:q], {:page => params[:page]})
        else
            redirect_to search_posts_groups_url(:q => params[:q])
        end
    end
    
    def search_posts
        if params[:q].nil? || params[:q].blank?
            redirect_to_referer groups_url
        else
            @posts = GroupPost.paginate_search(params[:q], {:page => params[:page]})
	end
    end
    
    def search_users
        if params[:id].nil?
            redirect_to_referer groups_url
        else
            @group = Group.find(:first, :conditions => ["id = ?", params[:id]])
            if @group.nil?
                redirect_to_referer groups_url
            else
                if params[:q].nil? || params[:q].blank?
                    redirect_to_referer group_url(@group)
                else
                    @users = User.paginate_search(params[:q], {:page => params[:page]}, {:conditions => ["users.id = group_users.user_id and group_users.group_id = ? ", params[:id]], :from => "users, group_users", :select => "users.*"})
                end
            end
        end
    end
    
    def all
        @groups = Group.paginate :page => params[:page], :order => "created_at desc"
        @page_title = '浏览全部小组'
    end
    
    def show
        @group = Group.find(params[:id])

        respond_to do |format|
            format.html do
                @new_users = @group.users.find(:all, :order => 'created_at desc limit 8')
                @posts = GroupPost.paginate_by_group_id @group, :include => [ :user, :group ], :page => params[:page], :order => "replied_at desc"
                @tags = group_tags(@group.id)
                @like_groups = get_users_like_groups(@group.users)
                @like_groups.delete(@group)
                @page_title = @group.title + '小组'
            end
            format.rss  do
                @posts = GroupPost.find_all_by_group_id @group, :include => [ :user, :group ], :order => "replied_at desc", :limit => "25"
                render :action => "show.rxml", :layout => false
            end
        end
    end
      
    def users
        @group = Group.find(params[:id])
        #@users = User.paginate :conditions => ["gu.group_id = ?", @group.id], :include => [ :community, :district ], :joins => "as us inner join group_users as gu on us.id = gu.user_id", :select => "us.*", :page => params[:page]
        @users = @group.users.paginate :include => [ :community, :district ], :page => params[:page]
        @page_title = @group.title + '小组 - 成员'
    end
  
    def manage_users
        @group = Group.find(params[:id])
        redirect_to group_url(@group) unless @group.is_admin?(current_user)
        #@users = User.paginate :conditions => ["gu.group_id = ?", @group.id], :joins => "as us inner join group_users as gu on us.id = gu.user_id", :select => "us.*", :page => params[:page]
        @users = @group.users.paginate :include => [ :community, :district ], :page => params[:page]
        @page_title = @group.title + '小组 - 成员'
    end
  
    def new
        @group = Group.new
        @page_title = '成立新的小组'
    end
  
    def create
        @group = Group.new(params[:group])
        Group.transaction do
            @group.save!
            #current_user.groups.push_with_attributes(@group, :is_admin => 't')
            group_users = GroupUser.new(:user => current_user, :group => @group, :is_admin => 't')
            group_users.save!
            current_user.add_scores(5)
        end
        flash[:notice] = '创建组成功.'
        redirect_to group_url(@group)
        rescue ActiveRecord::RecordInvalid
        render :action => 'new'
    end
  
    def edit
        @group = Group.find(params[:id])
        if !@group.is_admin?(current_user)
            #error_page("只有小组管理员才可以进行此操作。")
            raise ActiveRecord::RecordNotFound
        else
            @page_title = '编辑' + @group.title + '小组资料'
        end
    end
    
    def update
        @group = Group.find(params[:id])
        if @group.update_attributes(params[:group])
            redirect_to group_url(@group)
        else
            render :action => 'edit'
        end
    end
  
    def update_icon
        @page_title = '更新小组图标'
        @group = Group.find(params[:id])
        if !@group.is_admin?(current_user)
            #error_page("只有小组管理员才可以进行此操作。")
            raise ActiveRecord::RecordNotFound
        else
            return unless request.post?
            if params[:group][:image].nil?
                render group_url(@group)
            else
                @group.image = params[:group][:image]
                @group.save!
                flash[:notice] = '小组图标信息已经成功更新.'
                redirect_to edit_group_url(@group)
            end
        end
    end
  
    def newpost
        @group = Group.find(params[:id])
        @page_title = @group.title + ' - 发言'
        @post = GroupPost.new(params[:post])
        @user_tags = user_tags(current_user.id)
        @all_users_tags = user_tags
        if current_user.is_group_user(@group)
            return unless request.post?
            @post.replied_at = Time.now.utc
            @post.save!
            @post.tag_with(params[:newpost][:tags])
            current_user.posts << @post
            current_user.add_scores(3)
            redirect_to group_post_url(@post.group, @post)
        else
            #error_page("你必须加入这个小组才能发言.")
            #raise ActiveRecord::RecordNotFound
            flash[:notice] = "你必须加入这个小组才能发言."
            redirect_to group_url(@group)
        end
        rescue ActiveRecord::RecordInvalid
        render :action => 'newpost'
    end
  
    private
    def group_tags(id)
        tags = Tag.tags(:limit => 30, :order => "updated_at desc", :type => "group", :which => id)
    end
  
    def groups_tags(groups)
        alltags = Hash.new
        for group in groups
            tags = Tag.tags(:limit => 30, :order => "updated_at desc", :type => "group", :which => group.id)
            alltags[:"#{group.title}"] = tags
        end
        alltags
    end
    
end
